package oracle.springbootxm.controller;


import oracle.springbootxm.pojo.GoodsInfo;
import oracle.springbootxm.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.List;

@Controller
public class FileController {

    @Autowired
    private GoodsService goodsService;

    @RequestMapping("/uploadPage")
    public String uploadPage() {
        return "uploadPage";
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String upload(HttpServletRequest req, @RequestParam("file") MultipartFile file, Model m, @RequestParam("newgoodsname") String goodsname,@RequestParam("newgoodsdesc") String goodsdesc, @RequestParam("newgoodsprice") double goodsprice, @RequestParam("newgoodscount") int goodscount, HttpSession session) {
        try {
            String fileName = System.currentTimeMillis()+file.getOriginalFilename();
            String destFileName=req.getServletContext().getRealPath("")+"jsp"+File.separator+fileName;

            File destFile = new File(destFileName);
            destFile.getParentFile().mkdirs();
            file.transferTo(destFile);

            System.out.println(fileName);
            m.addAttribute("fileName",fileName);
            InputStream is = new FileInputStream(new File("D:\\Users\\Desktop\\lyf\\sunjobr\\oracle\\springbootxm\\src\\main\\webapp\\jsp\\"+fileName+""));
            OutputStream os = new FileOutputStream(new File("D:\\Users\\Desktop\\lyf\\sunjobr\\oracle\\springbootxm\\src\\main\\resources\\templates\\jsp\\"+fileName+""));
            int ch = is.read();
            while (ch != -1) {
                os.write(ch);
                ch = is.read();
            }
            is.close();
            os.close();

            GoodsInfo goodsInfo = new GoodsInfo();
            goodsInfo.setGoodsname(goodsname);
            goodsInfo.setGoodscount(goodscount);
            goodsInfo.setGoodsdesc(goodsdesc);
            goodsInfo.setGoodspic("jsp/"+fileName);
            goodsInfo.setGoodsprice(goodsprice);
            goodsService.addNewGoods(goodsInfo);
//            GoodsInfo goodsInfo1 = goodsService.querynewGoods(goodsInfo.getGoodsname());
//            List list = (List) session.getAttribute("list");
//            list.add(goodsInfo1);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return "上传失败," + e.getMessage();
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败," + e.getMessage();
        }

        return "addgoods";
    }
}
